package br.unicamp.ic.lis.docseaservice.model.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import br.unicamp.ic.lis.docseaservice.exception.DBException;
import br.unicamp.ic.lis.docseaservice.utils.PropertiesUtils;

public class ConnectionHandler {

	private static final String DB_DRIVER = PropertiesUtils
			.getString("db.driver");
	private static final String DB_PASSWORD = PropertiesUtils
			.getString("db.password");
	private static final String DB_USER = PropertiesUtils.getString("db.user");
	private static final String DB_URL = PropertiesUtils.getString("db.url");

	private static final String FAILED_TO_LOAD_DRIVER = "Failed to load driver "
			+ DB_DRIVER;
	private static final String FAILED_TO_OPEN_CONNECTION = "Failed to open connection";
	private static Logger LOG = Logger.getLogger(ConnectionHandler.class);

	/**
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			Class.forName(DB_DRIVER);
			Connection connection = DriverManager.getConnection(DB_URL,
					DB_USER, DB_PASSWORD);
			((org.postgresql.PGConnection) connection).addDataType("geometry",
					Class.forName("org.postgis.PGgeometry"));
			((org.postgresql.PGConnection) connection).addDataType("box3d",
					Class.forName("org.postgis.PGbox3d"));
			((org.postgresql.PGConnection) connection).addDataType("geography",
					Class.forName("org.postgis.PGgeometryLW"));
			return connection;
		} catch (ClassNotFoundException e) {
			LOG.error(FAILED_TO_LOAD_DRIVER, e);
			throw new DBException(FAILED_TO_LOAD_DRIVER, e);
		} catch (SQLException e) {
			LOG.error(FAILED_TO_OPEN_CONNECTION, e);
			throw new DBException(FAILED_TO_OPEN_CONNECTION, e);
		}
	}

}
